<template>
  <div class="prompt-field">
    <el-input
      v-model="localValue"
      type="textarea"
      :rows="4"
      :placeholder="placeholder"
      @blur="handleBlur"
    />
    
    <!-- AI 辅助按钮 -->
    <div v-if="aiAssist" class="ai-assist">
      <el-tooltip content="使用 AI 润色提示词">
        <el-button
          type="primary"
          :icon="Magic"
          circle
          plain
          :loading="polishing"
          @click="handlePolish"
        />
      </el-tooltip>
    </div>
    
    <!-- 常用提示词 -->
    <div class="common-prompts">
      <el-tag
        v-for="prompt in commonPrompts"
        :key="prompt"
        class="prompt-tag"
        @click="appendPrompt(prompt)"
      >
        {{ prompt }}
      </el-tag>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Magic } from '@element-plus/icons-vue'
import axios from 'axios'

const props = defineProps<{
  modelValue: string
  placeholder?: string
  aiAssist?: boolean
}>()

const emit = defineEmits(['update:modelValue'])

// 本地值
const localValue = ref(props.modelValue)

// 同步值
watch(() => props.modelValue, (newValue) => {
  if (newValue !== localValue.value) {
    localValue.value = newValue
  }
})

// 常用提示词
const commonPrompts = [
  'masterpiece',
  'best quality',
  'highly detailed',
  'ultra detailed',
  '8k uhd',
  'high resolution'
]

// 是否正在润色
const polishing = ref(false)

// 处理失去焦点
const handleBlur = () => {
  emit('update:modelValue', localValue.value)
}

// 追加提示词
const appendPrompt = (prompt: string) => {
  if (localValue.value) {
    localValue.value += `, ${prompt}`
  } else {
    localValue.value = prompt
  }
  emit('update:modelValue', localValue.value)
}

// 处理 AI 润色
const handlePolish = async () => {
  if (!localValue.value) {
    ElMessage.warning('请先输入提示词')
    return
  }
  
  polishing.value = true
  try {
    const response = await axios.post(
      `${import.meta.env.VITE_API_URL}/ai/polish`,
      {
        prompt: localValue.value
      }
    )
    localValue.value = response.data.result
    emit('update:modelValue', localValue.value)
    ElMessage.success('润色成功')
  } catch (error: any) {
    ElMessage.error(`润色失败: ${error.message}`)
  } finally {
    polishing.value = false
  }
}
</script>

<style scoped lang="scss">
.prompt-field {
  position: relative;
  
  .ai-assist {
    position: absolute;
    right: 8px;
    top: 8px;
  }
  
  .common-prompts {
    margin-top: 8px;
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    
    .prompt-tag {
      cursor: pointer;
      
      &:hover {
        opacity: 0.8;
      }
    }
  }
}
</style> 